﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Yyyg.IBLL;
using Yyyg.WebUI.Models;

namespace Yyyg.WebUI.Controllers
{
    public class UserLoginController : Controller
    {
        IMemberService users;

        public UserLoginController(IMemberService users)
        {
            this.users = users;
        }

        [HttpGet]
        public ActionResult Login(int? annul)
        {
            //指示是否注销该用户
            if (annul != null && annul == 1)
            {
                FormsAuthentication.SignOut();
            }
            Session["returnurl"] = Request.QueryString["ReturnUrl"];
            ReVerifyCode();
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserLoginVM info)
        {
            //控件验证
            if (!this.ModelState.IsValid) goto end;
            //验证码判断
            var fc = this.Session["login_verifyCode"].ToString().ToLower();
            if (fc != info.VerifyCode.ToLower())
            {
                ModelState.AddModelError("VerifyCode", "×验证码不正确");
                goto end;
            }
            //检测用户是否存在
            if (!users.HasUser(info.Account))
            {
                ModelState.AddModelError("Account", "×账号不存在");
                goto end;
            }
            try
            {
                string pwd = RSASingle.Decrypt(info.Pwd);
                //密码匹配判断
                if (!users.LoginCheck(info.Account, pwd))
                {
                    ModelState.AddModelError("Pwd", "×密码错误");
                    goto end;
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("Pwd", "×RSA解析失败");
                goto end;
            }

            var user = users.GetUser(info.Account);
            this.Session["login_verifyCode"] = null;
            //颁发Forms验证令牌
            FormsAuthentication.SetAuthCookie(user.Uid.ToString(), info.Remember);
            ReVerifyCode();
            var rturl = Session["returnurl"]?.ToString();
            Session["returnurl"] = null;
            return Redirect(rturl ?? "/home/index");
        end:
            //更新验证码         
            ReVerifyCode();
            return View(info);
        }

        //获取base64验证码图片数据
        public string ReloadverifyCode()
        {
            ReVerifyCode();
            string base64 = Convert.ToBase64String(this.ViewBag.VCodeImg);
            return base64;
        }

        //刷新验证码
        private void ReVerifyCode()
        {
            VerifyCode vcode = new VerifyCode();
            this.Session["login_verifyCode"] = vcode.Code;
            this.ViewBag.VCodeImg = vcode.ImgData;
        }
    }
}